package com.zesionlee.server.service

import com.alibaba.fastjson.JSONObject
import com.zesionlee.server.config.GlobalCurrent
import com.zesionlee.server.entity.DBEntity
import com.zesionlee.server.exception.CustomException
import org.springframework.stereotype.Service
import java.io.File

@Service
class DBService() {


    fun testDB(dbEntity: DBEntity) {
        GlobalCurrent.setDataSource(dbEntity)
        val msg = GlobalCurrent.getDataSource().test()
        if (msg != "success") {
            throw CustomException(msg)
        }

        dbEntity.status = 1
        GlobalCurrent.dbConfig!!.status = 1
        val dbConfigFile = File(GlobalCurrent.dataPath + "dbConfig.json")
        dbConfigFile.writeText(JSONObject.toJSONString(dbEntity), Charsets.UTF_8)
    }

    fun getDbConfig(): DBEntity {

        val config = GlobalCurrent.dbConfig
        if (config != null) {
            val msg = GlobalCurrent.getDataSource().test()
            config.status = if (msg == "success") 1 else 0
            GlobalCurrent.dbConfig!!.status = config.status
            return config
        }
        return DBEntity()
    }
}